package com.loto.insurance.oem.web.authority;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.loto.insurance.oem.web.entity.SessionUser;
import com.loto.insurance.oem.web.enumeration.ControllerPropertyEnum;
import com.loto.insurance.oem.web.enumeration.ResultTypeEnum;

public class AuthorityAnnotationInterceptor extends HandlerInterceptorAdapter {

  @Override
  public boolean preHandle(HttpServletRequest request,
	  HttpServletResponse response, Object handler) throws Exception {
	if (handler instanceof HandlerMethod) {
	  HandlerMethod handler2 = (HandlerMethod) handler;
	  OEMAuthority misAuthority = handler2
		  .getMethodAnnotation(OEMAuthority.class);

	  if (null == misAuthority) {
		// 没有声明权限,放行
		return true;
	  }

	  boolean aflag = false;
	  HttpSession session = request.getSession();
	  SessionUser user = (SessionUser) session.getAttribute("oem_user");
	  if (user != null) {
		// 校验权限
		aflag = AuthorityHelper.hasAuthority(user.getRoleId(),
		    misAuthority.authorityRole());
	  }
	  if (false == aflag) {
		if (misAuthority.resultType() == ResultTypeEnum.page) {
		  // 传统的登录页面
		  StringBuilder sb = new StringBuilder();
		  sb.append(request.getContextPath());
		  sb.append("/login?tourl=").append(
			  URLEncoder.encode(
			      request.getRequestURI()
			          + (request.getQueryString() == null ? "" : "?"
			              + request.getQueryString()), "utf-8"));
		  response.sendRedirect(sb.toString());
		} else if (misAuthority.resultType() == ResultTypeEnum.json) {
		  // ajax类型的登录提示
		  response.setCharacterEncoding("utf-8");
		  response.setContentType("application/json;charset=UTF-8");
		  OutputStream out = response.getOutputStream();
		  PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "utf-8"));
		  pw.println("{\"ok\":false,\"msg\":\""
			  + ControllerPropertyEnum.NOT_LOGIN + "\"}");
		  pw.flush();
		  pw.close();
		}
		return false;
	  }

	}
	return true;
  }
}